import Storage from "react-native-storage"
import AsyncStorage from "@react-native-async-storage/async-storage"

const MyStorage = function () {
    this.storage = new Storage({
        // maximum capacity, default 1000 key-ids
        size: 1000,

        // Use AsyncStorage for RN apps, or window.localStorage for web apps.
        // If storageBackend is not set, data will be lost after reload.
        storageBackend: AsyncStorage, // for web: window.localStorage

        // expire time, default: 1 day (1000 * 3600 * 24 milliseconds).
        // can be null, which means never expire.
        defaultExpires: 1000 * 3600 * 24,

        // cache data in the memory. default is true.
        enableCache: true,

        // if data was not found in storage or expired data was found,
        // the corresponding sync method will be invoked returning
        // the latest data.
        sync: {
            // we'll talk about the details later.
        }
    })
}

MyStorage.prototype = {
    save(key, data, expires = null) {
        this.storage.save({
            key,
            data,
            // 如果不指定过期时间，则会使用defaultExpires参数
            // 如果设为null，则永不过期
            expires
        })
    },
    load(key) {
        return new Promise((resolve) => {
            this.storage.load({
                key,
                // autoSync(默认为true)意味着在没有找到数据或数据过期时自动调用相应的sync方法
                autoSync: true,
                /**
                 * syncInBackground(默认为true)意味着如果数据过期
                 * 在调用sync方法的同时先返回已经过期的数据。
                 * 设置为false的话，则等待sync方法提供的最新数据(当然会需要更多时间)。
                 */
                syncInBackground: true,
            }).then(resolve)
                .catch(() => {
                    resolve(undefined)
                })
        })
    },
    remove(key) {
        this.storage.remove({
            key
        })
    }
}

Object.defineProperty(MyStorage.prototype, 'constructor', {
    enumerable: false,
    value: MyStorage
})

const storage = new MyStorage()

export default storage